import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Router, navigate } from 'utils/router';
import Loadable from 'utils/loadable';
import Nav from './nav';
import FullPage from 'components/FullPage';
import ProjectSecurityEntry from './projectSecurityEntry';
import * as actions from '../actions/index';
import { getProjectServices } from 'api';
import ListLoading from 'atComponents/ListLoading';
import { Header, Body, SideBar, BodyContent, Content } from '@alife/devops-ui';
import { enterPage, Perf } from 'utils/track';
import docs from 'utils/docs';
import intl from '../../../../../../../locale';

const sensitive_info_detection = 'sensitive_info_detection';
const dependency_analysis = 'dependency_analysis';
const pinpoint_detection = 'pinpoint_detection';

const checkServiceSwitchKeys = [sensitive_info_detection, dependency_analysis, pinpoint_detection];

const SensitiveInfo = Loadable({
  loader: () => import('../pages/sensitiveInfo'),
});

const DependencyAnalysis = Loadable({
  loader: () => import('../pages/dependencyAnalysis'),
});

// 源码漏洞检测
const Pinpoint = Loadable({
  loader: () => import('../pages/pinpoint'),
});

class Root extends Component {
  state = {
    isLoadingService: false,
    serviceData: {},
    plugins: [],
    isClosed: false,
  };

  componentDidMount() {
    const { pathResource } = window.FORCE;
    if (pathResource.isEmpty !== 'true') {
      this.setState({
        isLoadingService: true,
      });

      this.getServiceInfo();
    }
    this.fetchPlugins();

    enterPage('Repo-Security', {
      sendPerf: false,
    });

    // 初始化分支
    this.props.initBranchName();
  }

  fetchPlugins = () => {
    const { pathResource } = window.FORCE;
    this.setState({
      plugins: [
        {
          avatar_url:
            'https://img.alicdn.com/imgextra/i3/O1CN01zQjmzN1e3m2tsLFmF_!!6000000003816-2-tps-240-240.png',
          name: intl.get({
            id: 'code-assets.projectSecurity.containers.root.SensitiveInformationDetection',
            defaultMessage: '敏感信息检测',
          }),
          description: intl.get({
            id: 'code-assets.projectSecurity.containers.root.IdentifiesSensitiveContentAndReduces',
            defaultMessage: '识别编码敏感内容，降低涉密信息泄露风险',
          }),
          simple_desc: intl.get({
            id: 'code-assets.projectSecurity.containers.root.PayCloseAttentionToCode',
            defaultMessage: '时刻关注代码安全，降低敏感信息泄露风险。',
          }),
          desc_url: docs('sensitiveInformationDetection'),
          setting_url: `/${pathResource.fullPath}/settings/services`,
          key: sensitive_info_detection,
          // 是否是codeup内置扫描
          isCodeup: true,
          plugin: 'SECURITY',
          // 设置弹窗修改跳转路径参数
          _path: 'sensitive_info',
        },

        {
          avatar_url:
            'https://img.alicdn.com/imgextra/i3/O1CN01R9OiOs1pDoV2MBI3Z_!!6000000005327-2-tps-240-240.png',
          name: intl.get({
            id: 'code-assets.projectSecurity.containers.root.DependencyPackageVulnerabilityDetection',
            defaultMessage: '依赖包漏洞检测',
          }),
          description: intl.get({
            id: 'code-assets.projectSecurity.containers.root.MonitorSecurityVulnerabilitiesOfDependent',
            defaultMessage: '监测依赖软件包安全漏洞，提供修复方案建议与自动修复能力',
          }),
          simple_desc: intl.get({
            id: 'code-assets.projectSecurity.containers.root.IdentifyDependentSecurityVulnerabilitiesIn',
            defaultMessage: '及时识别依赖安全漏洞，提供修复方案建议。',
          }),
          desc_url: docs('dependencyPackageVulnerabilityDetection'),
          setting_url: `/${pathResource.fullPath}/settings/services`,
          key: dependency_analysis,
          isCodeup: true,
          isBeta: true,
          betaText: intl.get({
            id: 'code-assets.projectSecurity.containers.root.BetaAutomaticRepair',
            defaultMessage: 'Beta',
          }),
          plugin: 'SECURITY',
          _path: 'dependency_analysis',
        },

        {
          avatar_url:
            'https://img.alicdn.com/imgextra/i3/O1CN01wltNqE203hWqKqAwm_!!6000000006794-2-tps-88-88.png',
          name: intl.get({
            id: 'code-assets.projectSecurity.containers.root.SourceCodeVulnerabilityDetection',
            defaultMessage: '源码漏洞检测',
          }),
          description: intl.get({
            id: 'code-assets.projectSecurity.containers.root.DetectsHighRiskIssuesSuch',
            defaultMessage: '检测编码安全策略、输入合法性等高风险问题，支持引入路径追溯',
          }),
          simple_desc: intl.get({
            id: 'code-assets.projectSecurity.containers.root.IdentifyHighRiskIssuesSuch',
            defaultMessage: '识别源码安全策略、输入合法性等高风险问题',
          }),
          desc_url: docs('pinpoint'),
          setting_url: `/${pathResource.fullPath}/settings/services`,
          key: pinpoint_detection,
          isCodeup: false,
          plugin: 'SECURITY',
          _path: 'pinpoint',
          disablePageImg:
            'https://img.alicdn.com/imgextra/i1/O1CN01Xw5rNT1rOvKjxKwbY_!!6000000005622-2-tps-568-108.png',
          isBeta: true,
          betaText: 'Beta',
        },
      ],
    });
  };

  renderContent = () => {
    const { pathResource } = window.FORCE;
    const { serviceData, plugins } = this.state;
    if (!plugins.length) {
      return null;
    }
    return (
      <div className="project-security-content-body">
        <Router basepath={`/${pathResource.fullPath}/project_security`} primary={false}>
          <Pinpoint
            path="/pinpoint/:branch"
            serviceData={serviceData}
            plugin={plugins.find((plugin) => plugin.key === pinpoint_detection)}
          />
          <DependencyAnalysis
            path="/dependency_analysis/:branch"
            serviceData={serviceData}
            plugin={plugins.find((plugin) => plugin.key === dependency_analysis)}
          />
          <SensitiveInfo
            default
            serviceData={serviceData}
            plugin={plugins.find((plugin) => plugin.key === sensitive_info_detection)}
          />
        </Router>
      </div>
    );
  };

  getServiceInfo = () => {
    const { pathResource } = window.FORCE;
    getProjectServices()
      .then((result) => {
        const serviceData = result.integration_service_setting || {};
        const showSensitiveInfo = this.checkServiceInfo(serviceData);
        // 有数据且不是在当前面则href变化
        const { resourceSubject } = this.props.pageInfo;
        const path =
          resourceSubject && resourceSubject.subject === 'project_security' && resourceSubject.path
            ? resourceSubject.path
            : 'sensitive_info';

        if (showSensitiveInfo) {
          const defaultBranch = pathResource.defaultBranch || 'master';
          const branch =
            resourceSubject &&
            resourceSubject.subject === 'project_security' &&
            resourceSubject.path
              ? resourceSubject.revision
              : defaultBranch;
          const locationSearch = window.location.search || '';
          navigate(
            `/${pathResource.fullPath}/project_security/${path}/${encodeURIComponent(
              branch,
            )}${locationSearch}`,
          );
        }

        this.setState({
          serviceData,
          isLoadingService: false,
        });
      })
      .catch((err) => {
        console.error(err);
        this.setState({
          isLoadingService: false,
        });
      });
  };

  checkServiceInfo = (serviceData) => {
    for (const key of checkServiceSwitchKeys) {
      if (serviceData[key] && serviceData[key].enabled) {
        return true;
      }
    }
    return false;
  };

  handleToggle = (close) => {
    this.setState({
      isClosed: close,
    });
  };

  render() {
    const { isLoadingService, serviceData, plugins, isClosed } = this.state;
    const { projectInfo, pageInfo, root } = this.props;
    const { pinelineInfo } = root;
    if (isLoadingService) {
      return <ListLoading />;
    }
    const showEntry = !this.checkServiceInfo(serviceData);
    if (showEntry) {
      return (
        <FullPage>
          <Perf page="Repo-Security" />
          <ProjectSecurityEntry
            projectInfo={projectInfo}
            plugins={plugins}
            serviceData={serviceData}
            pageInfo={pageInfo}
          />
        </FullPage>
      );
    } else {
      return (
        <>
          <Header
            title={intl.get({
              id: 'code-assets.containers.projectSecurityTab.Safety',
              defaultMessage: '安全',
            })}
          />
          <Body>
            <SideBar closeable size="small" onToggle={this.handleToggle}>
              <Nav plugins={plugins} pinelineInfo={pinelineInfo} serviceData={serviceData} />
            </SideBar>
            <BodyContent>
              <Content className={isClosed ? 'no-nav' : ''}>{this.renderContent()}</Content>
            </BodyContent>
          </Body>
        </>
      );
    }
  }
}

export default connect(
  (state) => ({
    ...state.project.projectSecurity,
    projectInfo: state.project.root.projectInfo,
    pageInfo: state.root.pageInfo,
  }),
  (dispatch) => bindActionCreators(actions, dispatch),
)(Root);
